package com.meiyu.live.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.meiyu.live.BaseApplication;
import com.meiyu.live.comm.Constant;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BaseUtil
{

    public static boolean checkEmail(String email)
    {
        Pattern pattern = Pattern
                .compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    public static String saveBitmap(Bitmap img)
    {
        OutputStream os = null;
        try
        {
            File file = new File(String.format(Constant.FILE_PATH,
                    Long.toHexString(System.currentTimeMillis()) + ".jpg"));
            file.createNewFile();
            os = new FileOutputStream(file);
            img.compress(CompressFormat.JPEG, 80, os);
            return file.getAbsolutePath();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 鍥剧墖鍦嗗舰澶勭悊
     * 
     * @param img
     * @return
     */
    public static Bitmap bitmapCircle(Bitmap img)
    {
        if (img == null)
        {
            return null;
        }
        // int padding =
        // BaseApplication.getApp().getResources().getDimensionPixelOffset(R.dimen.header_padding);
        int w = img.getWidth();
        int h = img.getHeight();
        int size = w > h ? h : w;
        Paint p = new Paint();
        p.setColor(Color.WHITE);
        p.setAntiAlias(false);
        Bitmap bitmap = Bitmap.createBitmap(size, size, Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawCircle(size / 2, size / 2, size / 2, p);
        p.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(img, 0, 0, p);
        p.setXfermode(null);
        p.setStrokeWidth(10);
        p.setAlpha(0x33);
        p.setStyle(Paint.Style.STROKE);
        // canvas.drawCircle(size / 2, size / 2, size / 2, p);

        return bitmap;
    }

    public static String findToken(String cookies)
    {
        if (TextUtils.isEmpty(cookies))
        {
            return null;
        }
        String[] strs = cookies.split(" ");
        StringBuffer sb = new StringBuffer();
        for (String str : strs)
        {
            if (str.startsWith("JSESSIONID"))
            {
                sb.append(str);
            }
            else if (str.startsWith("HttpOnlyuserToken"))
            {
                sb.append(str.replace("HttpOnlyuserToken", "userToken"));
            }
        }
        return sb.toString();
    }

    // public static Drawable getVideoRound(Context context, int size) {
    // DisplayMetrics display = context.getResources().getDisplayMetrics();
    // int imgWidht = display.widthPixels;
    // int imgHeight = display.heightPixels / 2;
    // Bitmap bg = ((BitmapDrawable)
    // context.getResources().getDrawable(R.drawable.bg_home_cut)).getBitmap();
    // Bitmap output = Bitmap.createBitmap(imgWidht, imgHeight,
    // Config.ARGB_8888);
    // Canvas canvas = new Canvas(output);
    // Paint paint = new Paint();
    // paint.setAntiAlias(true);
    // canvas.drawBitmap(bg, new Rect(0, 0, bg.getWidth(), bg.getHeight()), new
    // Rect(0, 0, imgWidht, imgHeight), paint);
    // paint.setXfermode(new PorterDuffXfermode(Mode.XOR));
    // canvas.drawCircle(imgWidht / 2, imgHeight - (size / 2), size / 2 - 15,
    // paint);
    // return new BitmapDrawable(context.getResources(), output);
    // }

    public static String formatString(String time)
    {

        if (time.length() >= 14)
        {
            String year = time.substring(0, 4);
            String month = time.substring(4, 6);
            String day = time.substring(6, 8);
            String hour = time.substring(8, 10);
            String minu = time.substring(10, 12);
            String sec = time.substring(12, 14);
            return year + "-" + month + "-" + day + " " + hour + ":" + minu
                    + ":" + sec;
        }
        return time;
    }

    public static String formatString1(String time)
    {

        if (time.length() >= 14)
        {
            String year = time.substring(0, 4);
            String month = time.substring(4, 6);
            String day = time.substring(6, 8);
            return year + "/" + month + "/" + day;
        }
        return time;
    }

//    public static List<ImageFolder> getPhotoThumbnail()
//    {
//        List<ImageFolder> folders = new ArrayList<ImageFolder>();
//        // 查询的列
//        String[] projection = new String[] {MediaStore.Images.Media._ID,
//                MediaStore.Images.Media.BUCKET_ID, // 直接包含该图片文件的文件夹ID，防止在不同下的文件夹重名
//                MediaStore.Images.Media.BUCKET_DISPLAY_NAME, // 直接包含该图片文件的文件夹名
//                MediaStore.Images.Media.DISPLAY_NAME, // 图片文件名
//                MediaStore.Images.Media.DATA // 图片绝对路径
//        };
//        ImageFolder item = new ImageFolder();
//        ImageFile file = null;
//        ContentResolver cr = BaseApplication.getApp().getContentResolver();
//        Cursor cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
//                projection, null, null, MediaStore.Images.Media.BUCKET_ID
//                        + " desc");
//        while (cursor.moveToNext())
//        {
//            String id = cursor.getString(cursor
//                    .getColumnIndex(MediaStore.Images.Media.BUCKET_ID));
//            if (item.getId() == null || !item.getId().equals(id))
//            {
//                item = new ImageFolder();
//                item.setId(id);
//                item.setFolder(cursor.getString(cursor
//                        .getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME)));
//                folders.add(item);
//            }
//            file = new ImageFile();
//            file.setFileId(cursor.getLong(cursor
//                    .getColumnIndex(MediaStore.Images.Media._ID)));
//            file.setFileName(cursor.getString(cursor
//                    .getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME)));
//            file.setPath(cursor.getString(cursor
//                    .getColumnIndex(MediaStore.Images.Media.DATA)));
//            item.getFiles().add(file);
//        }
//        cursor.close();
//        return folders;
//    }

    public static void clearDownFile()
    {
        delDir(Constant.DOWN_PATH, false);
    }

    public static void delDir(String path, boolean isDelDir)
    {
        File file = new File(path);
        if (!file.exists() || !file.isDirectory())
        {
            return;
        }
        File[] tempList = file.listFiles();
        for (File item : tempList)
        {
            if (item.isFile())
            {
                item.delete();
            }
            else
            {
                delDir(item.getAbsolutePath(), true);
            }
        }
        if (isDelDir)
        {
            file.delete();
        }
    }

    public static boolean saveWordProview(Bitmap img, String id)
    {
        File file = new File(Constant.DOWN_PATH, id + ".jpg");
        if (file.exists() || img == null)
        {
            return false;
        }
        try
        {
//            file.createNewFile();
            OutputStream os = new FileOutputStream(file);
            img.compress(CompressFormat.JPEG, 100, os);
            os.flush();
            os.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            file.delete();
            return false;
        }
        return true;
    }

    public static boolean isNetworkConnected()
    {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) BaseApplication
                .getApp().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null)
        {
            return mNetworkInfo.isAvailable();
        }
        return false;
    }

    public static String GetNetworkType()
    {
        String strNetworkType = "";

        ConnectivityManager mConnectivityManager = (ConnectivityManager) BaseApplication
                .getApp().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
        {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI)
            {
                strNetworkType = "0";
            }
            else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
            {
                String _strSubTypeName = networkInfo.getSubtypeName();

                Log.e("cocos2d-x", "Network getSubtypeName : "
                        + _strSubTypeName);

                // TD-SCDMA networkType is 17
                int networkType = networkInfo.getSubtype();
                switch (networkType)
                {
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN: // api<8 : replace
                                                             // by 11
                        strNetworkType = "1";
                        break;
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_B: // api<9 :
                                                               // replace by 14
                    case TelephonyManager.NETWORK_TYPE_EHRPD: // api<11 :
                                                              // replace by 12
                    case TelephonyManager.NETWORK_TYPE_HSPAP: // api<13 :
                                                              // replace by 15
                        strNetworkType = "2";
                        break;
                    case TelephonyManager.NETWORK_TYPE_LTE: // api<11 : replace
                                                            // by 13
                        strNetworkType = "3";
                        break;
                    default:
                        // http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信
                        // 三种3G制式
                        if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA")
                                || _strSubTypeName.equalsIgnoreCase("WCDMA")
                                || _strSubTypeName.equalsIgnoreCase("CDMA2000"))
                        {
                            strNetworkType = "2";
                        }
                        else
                        {
                            strNetworkType = _strSubTypeName;
                        }

                        break;
                }

                Log.e("cocos2d-x",
                        "Network getSubtype : "
                                + Integer.valueOf(networkType).toString());
            }
        }

        Log.e("cocos2d-x", "Network Type : " + strNetworkType);

        return strNetworkType;
    }
    
}
